import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Progress, Balloon } from '@teamix/ui';
import { ButtonIcon, YunxiaoIcon } from '@alife/devops-ui';
import utils from 'utils';
import docs from 'utils/docs';
import track from 'utils/track';
import { navigateOpen } from 'utils/router';
import GcConfirm from './gcConfirm';
import intl from '../../../../../../../../../../locale';
export default class BaseForm extends Component {
  static propTypes = {
    GC: PropTypes.object,
  };

  static defaultProps = {
    GC: {},
  };

  componentDidMount() {
    this.props.getSize();
    this.props.getGC();
  }

  // 默认2G lfs信息单位是字节
  getProgressProps = (a, b, isLfs = false) => {
    return {
      percent: a && (a / b) * 100 < 1 ? 1 : (a / b) * 100,
      color: (a / b) * 100 >= 90 ? '#e62412' : '#70b8ff',
      size: 'large',
      textRender: () => {
        return (
          <div className="setting-progress-content">
            {isLfs ? (
              <span>
                {utils.getSizeStr(a) || 0}&nbsp;/&nbsp;{utils.getSizeStr(b)}
              </span>
            ) : (
              <span>
                {a.toFixed(2)}M&nbsp;/&nbsp;{(b / 1024).toFixed(2)}G
              </span>
            )}

            {!isLfs && (
              <span className="progress-tip">
                <Balloon closable={false} trigger={<ButtonIcon name="question-line" />} align="t">
                  <a href={docs('storageCapacity')} target="_blank" rel="noreferrer">
                    {intl.get({
                      id: 'code-assets.containers.storageForm.WhatIsTheStorageCapacity',
                      defaultMessage: '我的代码库存储空间容量是多少？',
                    })}
                  </a>
                </Balloon>
              </span>
            )}
          </div>
        );
      },
    };
  };

  handleClear = (immediately) => {
    const { isPostingGC, GC } = this.props;
    if (isPostingGC || GC.status === 'started') {
      return;
    }
    this.props.postGC(immediately);
  };

  getBtnTxt = () => {
    const { isPostingGC, GC, repo_size } = this.props;
    if (isPostingGC || GC.status === 'started') {
      return <YunxiaoIcon type="loading-fill" />;
    }
    if (!repo_size.last_gc_time) {
      return intl.get({
        id: 'code-assets.containers.storageForm.ClearImmediately',
        defaultMessage: '立刻清理',
      });
    }
    return intl.get({
      id: 'code-assets.containers.storageForm.ClearAgain',
      defaultMessage: '再次清理',
    });
  };

  goLfsList = () => {
    const { pathResource } = window.FORCE;
   navigateOpen(`/${pathResource.fullPath}/settings/lfs`, '_blank');
    track({
      action: 'view_lfs_file',
      page: '',
      type: '',
      control: 'tag',
    });
  };

  getbtnhander = () => {
    if (window.FORCE.pathResource.isEmpty === 'true') {
      return (
        <Balloon.Tooltip
          align="b"
          trigger={
            <Button type="primary" disabled>
              {this.getBtnTxt()}
            </Button>
          }
        >
          {intl.get({
            id: 'code-assets.containers.storageForm.InitializeTheCodeLibraryFirst',
            defaultMessage: '请先初始化代码库',
          })}
        </Balloon.Tooltip>
      );
    } else {
      return <Button type="primary">{this.getBtnTxt()}</Button>;
    }
  };

  render() {
    const { repo_size, pageInfo, lfsInfo, isPostingGC, GC } = this.props;
    const progressProps = this.getProgressProps(
      repo_size,
      pageInfo.pathResource.repoLimitSize || 2048,
    );

    // lfs单位是字节，需要转化
    // const lfsProgressProps = lfsInfo.opened
    //   ? this.getProgressProps(Number(lfsInfo.used), Number(lfsInfo.total), true)
    //   : {};
    const isLoadingGC = isPostingGC || GC.status === 'started';

    const size = utils.getSizeStr(Number(lfsInfo.used));
    const { length } = size;
    const number = size.substring(0, length - 1);
    const unit = size.substring(length - 1);
    const lsfUsed = size ? `${number} ${unit}` : '0 G';
    return (
      <div className="storage-form">
        <div className="change-path setting-card-item storage-item">
          <div className="setting-card-subtitle">
            {intl.get({
              id: 'code-assets.containers.storageForm.RepositoryGc',
              defaultMessage: '存储库 GC',
            })}
          </div>
          <div className="setting-card-subtitle-desc">
            {intl.get({
              id: 'code-assets.containers.storageForm.OptimizesTheStorageSpaceOf',
              defaultMessage: '用于优化代码库存储空间，压缩存储库对象，减少磁盘占用。',
            })}

            <br />
            {intl.get({
              id: 'code-assets.containers.storageForm.WhenGitGcAndOther',
              defaultMessage:
                '当 git gc 与其他 git\n                操作的进程并行处理时，可能会导致其他进程失败或者可能会损坏存储库。',
            })}

            <br />
            {intl.get({
              id: 'code-assets.containers.storageForm.SelectTheOffPeakPeriod',
              defaultMessage: '请选择 git 操作的低峰期进行清理操作。',
            })}
          </div>
          <div>
            <div className="progress-wrapper">
              <div className="progress-info">
                <Progress {...progressProps} />
              </div>
            </div>
            <div className="clear-btn-text">
              <GcConfirm
                trigger={<Button type="primary">{this.getBtnTxt()}</Button>}
                onChange={this.handleClear}
                isLoading={isLoadingGC}
              />

              {repo_size.last_gc_time ? (
                <span className="text">
                  {intl.get({
                    id: 'code-assets.containers.storageForm.LastCleanupIn',
                    defaultMessage: '上次清理于',
                  })}

                  {utils.getBeautyTime(repo_size.last_gc_time).toLowerCase()}
                </span>
              ) : null}
            </div>
          </div>
        </div>
        {lfsInfo.opened && (
          <div className="change-path setting-card-item storage-item" style={{ marginTop: '16px' }}>
            <div className="setting-card-subtitle">
              {intl.get({
                id: 'code-assets.containers.storageForm.LargeFileStorage',
                defaultMessage: '大文件存储',
              })}
            </div>
            <div className="setting-card-subtitle-desc">
              已使用 {lsfUsed}，了解大文件存储（Git LFS）空间使用详情，请查看{' '}
              <a className="no-href-with-click" onClick={this.goLfsList}>
                {intl.get({
                  id: 'code-assets.containers.storageForm.GitLfsFileList',
                  defaultMessage: 'Git LFS 文件列表',
                })}
              </a>
            </div>
            {/* <div>
              <div className="progress-wrapper">
                <div className="progress-info">
                  <Progress {...lfsProgressProps} />
                </div>
              </div>
            </div> */}
          </div>
        )}
      </div>
    );
  }
}
